use std::sync::Arc;
use tokio::sync::Mutex;
use crate::ui::app::AppData;
use crate::git::manager::GitManager;
use crate::core::message::{EventSender, AppEvent};

// 应用全局状态
#[derive(Clone)]
pub struct AppState {
    pub app_data: Arc<Mutex<AppData>>,
    pub git_manager: GitManager,
    pub event_sender: EventSender,
}

impl AppState {
    pub fn new(app_data: AppData, event_sender: EventSender) -> Self {
        let app_data = Arc::new(Mutex::new(app_data));
        let git_manager = GitManager::new(event_sender.clone());

        Self {
            app_data,
            git_manager,
            event_sender,
        }
    }

    // 辅助方法，用于更容易地更新应用数据
    pub async fn update_app<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut AppData) -> R,
    {
        let mut app = self.app_data.lock().await;
        let result = f(&mut app);

        // 通知界面需要重新渲染
        let _ = self.event_sender.send(AppEvent::Render).await;

        result
    }
}

